package com.asfaloth.wss.dao.impl;

import com.asfaloth.wss.dao.IWssUserDao;
import com.asfaloth.wss.entity.WssUser;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by 80002004 on 2017/2/6.
 */
@Repository
public class WssUserDaoImpl implements IWssUserDao {

    static Logger logger = LoggerFactory.getLogger(WssUserDaoImpl.class);
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void insert(WssUser user) {
        mongoTemplate.insert(user);
        logger.info("user has inserted successfuly, user: {}", new Gson().toJson(user));
    }

    @Override
    public List<WssUser> find(WssUser user, int skip, int limit) {
        Query query = this.createQuery(user);
        query.skip(skip);
        query.limit(limit);
        return mongoTemplate.find(query, WssUser.class);
    }

    public Query createQuery(WssUser user) {
        Query query = new Query();
        if(null != user.getId())
        {
            Criteria criteria = Criteria.where("id").is(user.getId());
            query.addCriteria(criteria);
        }

        if(StringUtils.isNotEmpty(user.getUsername()))
        {
            Criteria criteria = Criteria.where("username").is(user.getUsername());
            query.addCriteria(criteria);
        }

        if(null != user.getAge())
        {
            Criteria criteria = Criteria.where("age").is(user.getAge());
            query.addCriteria(criteria);
        }

        return query;
    }
}
